<template>
  <div class="msg-box" :class="{ right: right }">
    <time-msg v-if="props.msg.isShowTime" :content="props.msg.createTime" class="mb-[10px]" />
    <template v-if="msg.type === 'recall'">
      <recall-msg :msg="msg" />
    </template>
    <div v-else class="msg-box-wrapper" :class="{ right: right }">
      <avatar
        :info="userInfo"
        size="40px"
        class="mr-[5px] ml-[5px]"
      />
      <div class="msg-box-info">
        <!-- 用户信息 -->
        <div class="mgs-box-user-info" :class="{ right: right }">
          <div class="msg-username">
            <span v-if="isGroupLeader" class="group-leader-tag">群主</span>
            {{ userInfo.name }}
          </div>
        </div>
        <!-- 消息内容 -->
        <msg-content :right="right" :msg="props.msg" />
        <!-- 引用信息 -->
        <div v-if="props.msg.referenceMsg" class="msg-box-info-reference" :class="{ right: right }">
          <reference-content :msg="props.msg.referenceMsg" />
          <i class="iconfont icon-zhiding ml-[5px]" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import MsgContent from '@/components/Msg/MsgContent.vue'
import Avatar from '@/components/Avatar.vue'
import RecallMsg from '@/components/Msg/MsgContent/RecallMsg.vue'
import ReferenceContent from '@/components/Msg/ReferenceContent.vue'
import TimeMsg from '@/components/Msg/MsgContent/TimeMsg.vue'
import { useUserInfoStore } from '@/stores/useUserInfoStore.js'
import { useChatMsgStore } from '@/stores/useChatMsgStore.js'
import UserlistApi from '@/api/userList'

const userInfoStore = useUserInfoStore()
const msgStore = useChatMsgStore()

const props = defineProps({
  msg: Object,
  user: Object,
})

// 响应式字段：是否是群主
const isGroupLeaderMap = ref(new Map())

// 计算属性：获取用户信息
const userInfo = computed(() => {
  return msgStore.userListMap.get(props.msg.fromId) || {}
})

// 计算属性：判断是否为群主
const isGroupLeader = computed(() => {
  return isGroupLeaderMap.value.get(props.msg.fromId) === true
})

/**
 * 判断当前用户是否为群组的创建者
 */
const checkIsGroupLeader = async (groupId, userId) => {
  if (!groupId || !userId) {
    console.warn('缺少必要参数：groupId 或 userId')
    return false
  }

  try {
    const response = await UserlistApi.getGroupOwnerId({ groupId })

    if (response.code === 0) {
      const leaderId = response.data
      const result = leaderId === userId

      // 使用 Map 存储每个用户的判断结果
      isGroupLeaderMap.value.set(userId, result)

    } else {
      console.warn('未找到群主信息或接口返回异常')
      isGroupLeaderMap.value.set(userId, false)
    }
  } catch (error) {
    console.error('获取群主信息失败:', error)
    isGroupLeaderMap.value.set(userId, false)
  }
}

// 组件挂载时检查是否为群主
onMounted(() => {
  const groupId = props.msg.toId // 根据实际情况替换
  const userId = props.msg.fromId
  if (userId) {
    checkIsGroupLeader(groupId, userId)
  }
})

// 监听 fromId 变化，动态更新是否为群主
watch(
  () => props.msg.fromId,
  (newUserId) => {
    if (newUserId) {
      const groupId = 'group_1' // 根据实际情况传入
      checkIsGroupLeader(groupId, newUserId)
    }
  }
)

const right = computed(() => {
  return props.msg.fromId === userInfoStore.userId
})
</script>

<style lang="less" scoped>
.msg-box {
  display: flex;
  margin-bottom: 20px;
  width: 100%;
  flex-direction: column;

  .msg-box-wrapper {
    display: flex;
    align-items: start;

    .msg-box-info {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      width: 100%;

      .mgs-box-user-info {
        display: flex;
        align-items: center;
        height: 30px;

        &.right {
          flex-direction: row-reverse;
        }

        .msg-username {
          color: rgba(var(--text-color), 0.7);
          user-select: none;
          font-size: 14px;
          font-weight: 600;
        }

        .group-leader-tag {
          margin-left: 5px;
          background-color: #ffd700; /* 群主标签背景色 */
          color: #333; /* 群主文字颜色 */
          font-size: 12px;
          padding: 2px 6px;
          border-radius: 4px;
        }

        .mgs-ip {
          color: rgba(var(--text-color), 0.6);
          user-select: none;
          font-size: 12px;
          font-weight: 600;
        }
      }

      .msg-box-info-reference {
        max-width: 60%;
        word-break: break-word;
        margin-top: 5px;
        padding: 2px 10px;
        border-radius: 4px;
        background-color: rgba(var(--text-color), 0.05);
        user-select: none;
        display: flex;
        font-size: 14px;
        color: rgba(var(--text-color), 0.7);
        border: rgba(var(--text-color), 0.07) 1px solid;

        &.right {
          flex-direction: row-reverse;

          i {
            margin-right: 10px;
            margin-left: 0;
          }
        }
      }
    }

    &.right {
      flex-direction: row-reverse;
    }
  }

  &.right {
    justify-content: flex-end;

    .msg-box-info {
      align-items: flex-end;
    }
  }
}
</style>
